package com;

import javax.swing.*;
import com.trusfort.redis.RedisServiceUtil;
import com.util.FileUtils;
import redis.clients.jedis.exceptions.JedisConnectionException;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

public class RedisKeyAdd {
    private static JTextField txtRedisAddress;
    private static JTextField txtRedisPassword;
    private static JTextField txtSavePath;
    private static JTextArea txtLog;
    private static JProgressBar progressBar;
    private static JTextArea txtResult;


    private final Map<String, Map<String, Long>> data = new ConcurrentHashMap<String, Map<String, Long>>();
    private final AtomicLong totalKeys = new AtomicLong(0);
    private static volatile boolean isRunning = false;

    public static void logInfo(String msg) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String cur = sdf.format(new Date());
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                txtLog.append(cur + " - " + msg + "\n");
                FileUtils.write(txtSavePath.getText() + "/logs/info.txt", cur + " [INFO] " + msg);
            }
        });
    }

    public void statInvalidField() {
        if (isRunning) {
            logInfo("已有任务在运行，请等待完成");
            return;
        }

        isRunning = true;
        totalKeys.set(0);
        data.clear();

        try {
            String redisAddress = txtRedisAddress.getText();
            String redisPassword = txtRedisPassword.getText();
            
//            RedisServiceUtil.init("single", redisAddress, 
//                    redisPassword.isEmpty() ? null : redisPassword);
            
            RedisServiceUtil.init("cluster", redisAddress, 
                    redisPassword.isEmpty() ? null : redisPassword);
            
            for(int m=0;m<100;m++) {
            	List<String> list = new ArrayList<String>();
            	for(int i=0;i<1000;i++) {
                  	String uuid =UUID.randomUUID().toString().replace("-","");
                      
                  	list.add(uuid+";"+uuid);
                  }	
            	RedisServiceUtil.set(list, 1800);
            	System.out.println("m---------------------"+m);
            }
            
            logInfo("所有分析完成，总计key数量: " + totalKeys.get());
            
            // 显示统计结果
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    txtResult.setText(formatResults(data));
                }
            });
            
        } catch (JedisConnectionException e) {
            logInfo("无法连接Redis: " + e.getMessage());
        } catch (Exception e) {
            logInfo("分析过程中出错: " + e.getMessage());
        } finally {
            isRunning = false;
        }
    }

    /**
     * 格式化统计结果为表格形式
     */
    /**
     * 格式化统计结果为表格形式
     */
    private String formatResults(Map<String, Map<String, Long>> data) {
        StringBuilder sb = new StringBuilder();
        sb.append("Redis内存统计结果:\n");
        sb.append("+------------------------------+--------------+----------------------+\n");
        sb.append("| Key Pattern                  | Key Count    | Memory Usage         |\n");
        sb.append("+------------------------------+--------------+----------------------+\n");
        
        long totalCount = 0;
        long totalMemory = 0;
        
        for (Map.Entry<String, Map<String, Long>> entry : data.entrySet()) {
            String pattern = entry.getKey();
            Map<String, Long> stats = entry.getValue();
            long count = stats.get("keys");
            long memory = stats.get("memory");
            
            sb.append(String.format("| %-28s | %,12d | %,18d |\n", 
                    pattern, count, memory));
            
            totalCount += count;
            totalMemory += memory;
        }
        
        sb.append("+------------------------------+--------------+----------------------+\n");
        sb.append(String.format("| %-28s | %,12d | %,18d |\n", 
                "TOTAL", totalCount, totalMemory));
        sb.append("+------------------------------+--------------+----------------------+\n");
        
        // 添加内存单位转换 - 只显示最大单位
        sb.append("\n内存使用情况:\n");
        if (totalMemory >= 1024 * 1024) {
            sb.append(String.format("总内存: %.2f MB\n", totalMemory / (1024.0 * 1024.0)));
        } else if (totalMemory >= 1024) {
            sb.append(String.format("总内存: %.2f KB\n", totalMemory / 1024.0));
        } else {
            sb.append(String.format("总内存: %d bytes\n", totalMemory));
        }
        
        return sb.toString();
    }

    public static void main(String[] args) {
        JFrame jf = new JFrame("Redis数据分析 (优化版)");
        jf.setSize(900, 700);
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        jf.setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        panel.setLayout(null);

        // 主机地址
        JLabel lblIp = new JLabel("Redis 地址:");
        lblIp.setBounds(20, 20, 80, 25);
        panel.add(lblIp);

        txtRedisAddress = new JTextField("192.168.1.170:6382");
        txtRedisAddress.setBounds(100, 20, 150, 25);
        panel.add(txtRedisAddress);

        // 端口
        JLabel lblPort = new JLabel("密码:");
        lblPort.setBounds(270, 20, 50, 25);
        panel.add(lblPort);

        txtRedisPassword = new JTextField("");
        txtRedisPassword.setBounds(320, 20, 80, 25);
        panel.add(txtRedisPassword);

        // 保存路径
        JLabel lblPath = new JLabel("保存路径:");
        lblPath.setBounds(20, 60, 80, 25);
        panel.add(lblPath);

        txtSavePath = new JTextField("D:/data/redis_exp/");
        txtSavePath.setBounds(100, 60, 300, 25);
        panel.add(txtSavePath);

        // 进度条
        progressBar = new JProgressBar(0, 1000);
        progressBar.setBounds(20, 100, 860, 20);
        progressBar.setStringPainted(true);
        panel.add(progressBar);

        // 日志区域
        JScrollPane logScrollPane = new JScrollPane();
        logScrollPane.setBounds(20, 130, 860, 200);
        panel.add(logScrollPane);

        txtLog = new JTextArea();
        txtLog.setEditable(false);
        logScrollPane.setViewportView(txtLog);

        // 结果区域
        JScrollPane resultScrollPane = new JScrollPane();
        resultScrollPane.setBounds(20, 340, 860, 300);
        panel.add(resultScrollPane);

        txtResult = new JTextArea();
        txtResult.setEditable(false);
        resultScrollPane.setViewportView(txtResult);

        // 控制按钮
        JButton btnStart = new JButton("开始分析");
        btnStart.setBounds(420, 20, 120, 60);
        btnStart.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        new RedisKeyAdd().statInvalidField();
                    }
                }).start();
            }
        });
        panel.add(btnStart);

        JButton btnStop = new JButton("停止");
        btnStop.setBounds(550, 20, 120, 60);
        btnStop.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                isRunning = false;
                logInfo("用户手动停止扫描");
            }
        });
        panel.add(btnStop);

        jf.setContentPane(panel);
        jf.setVisible(true);
    }
}